package com.reebake.ideal.servlet.core;

import cn.hutool.core.util.ObjUtil;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class ServletInputStreamWrapper extends ServletInputStream {

    private final InputStream sourceStream;

    private boolean finished = false;

    public ServletInputStreamWrapper(byte [] bytes) {
        if(ObjUtil.isNull(bytes)) {
            bytes = new byte[]{};
        }
        //构建一个普通的输入流
        this.sourceStream = new ByteArrayInputStream(bytes);
    }

    @Override
    public int read() throws IOException {
        int data = this.sourceStream.read();
        if (data == -1) {
            this.finished = true;
        }
        return data;
    }

    @Override
    public int available() throws IOException {
        return this.sourceStream.available();
    }

    @Override
    public void close() throws IOException {
        super.close();
        this.sourceStream.close();
    }

    @Override
    public boolean isFinished() {
        return this.finished;
    }

    @Override
    public boolean isReady() {
        return true;
    }

    @Override
    public void setReadListener(ReadListener readListener) {
        throw new UnsupportedOperationException();
    }
}
